io = require('socket.io')
const express = require('express')
const path = require('path')
const fs = require('fs')
const multer = require("multer")
const http = require('http')

var app = express();

app.use(express.static(__dirname));

app.use(express.static(path.join(__dirname, 'public')));

//配置diskStorage来控制文件存储的位置以及文件名字等
var storage = multer.diskStorage({
	//确定图片存储的位置
	destination: function(req, file, cb) {
		cb(null, './public/uploadImgs')
	},
	//![](http://images2017.cnblogs.com/blog/1283058/201802/1283058-20180201154342296-515041615.png)
	//确定图片存储时的名字,注意，如果使用原名，可能会造成再次上传同一张图片的时候的冲突
	filename: function(req, file, cb) {
		cb(null, Date.now() + file.originalname)
	}
});
//生成的专门处理上传的一个工具，可以传入storage、limits等配置
var upload = multer({
	storage: storage
});

//跨域处理
app.all('*', function(req, res, next) {
	res.header('Access-Control-Allow-Origin', '*');
	res.header('Access-Control-Allow-Headers', 'Content-Type');
	res.header('Access-Control-Allow-Methods', '*');
	res.header('Content-Type', 'application/json;charset=utf-8');
	next();
});

//接收上传图片请求的接口
app.post('/uploads', upload.single('file'), function(req, res, next) {
	//图片已经被放入到服务器里,且req也已经被upload中间件给处理好了（加上了file等信息）
	//线上的也就是服务器中的图片的绝对地址 
	var url = 'http://192.168.0.101:10005/uploadImgs/' + req.file.filename
	res.json({
		code: 200,
		data: url
	})
});

var server = app.listen(10005, '192.168.0.101');

var ws = io.listen(server);

// 检查昵称是否重复
var checkNickname = function(name) {
	for(var k in ws.sockets.sockets) {
		if(ws.sockets.sockets.hasOwnProperty(k)) {
			if(ws.sockets.sockets[k] && ws.sockets.sockets[k].nickname == name) {
				return true;
			}
		}
	}
	return false;
}
// 获取所有的昵称数组
var getAllNickname = function() {
	var result = [];
	for(var k in ws.sockets.sockets) {
		if(ws.sockets.sockets.hasOwnProperty(k)) {
			result.push({
				name: ws.sockets.sockets[k].nickname
			});
		}
	}
	return result;
}

//当前在线人数
var totalMember = 0

ws.on('connection', function(client) {
	console.log('\033[96msomeone is connect\033[39m \n');
	client.on('join', function(msg) {
		// 检查是否有重复
		if(checkNickname(msg)) {
			client.emit('nickname', '昵称有重复!');
		} else {
			client.nickname = msg;
			totalMember++
			ws.sockets.emit('announcement', '系统', msg + ' 加入了聊天室!', {
				type: 'join',
				name: getAllNickname()
			});
			console.log("-----------------------")
			ws.sockets.emit('announcement', '在线人数', totalMember);
			ws.sockets.emit('announcement', '用户数组', getAllNickname());
		}

	});

	// 监听发送消息
	client.on('send.message', function(msg) {
		client.broadcast.emit('send.message', client.nickname, msg);

	});

	//   setInterval(function(){
	//   	  client.broadcast.emit('send.message','系统',  "扫黑除恶，公正公平 ，民主和谐！！！！！！！！！！！！！！！！！");
	//   },80000)

	client.on('disconnect', function() {
		if(client.nickname) {
			totalMember--
			client.broadcast.emit('send.message', '系统', client.nickname + '离开聊天室!', {
				type: 'disconnect',
				name: client.nickname
			});
			client.broadcast.emit('send.message', '在线人数', totalMember);
			setTimeout(function() {

				client.broadcast.emit('send.message', '用户数组', getAllNickname());
			}, 100)
		}
	})

})